package com.wzh.test;

import java.util.Scanner;

/**
 * 使用循环数组模拟一个队列
 * 提供四个方法
 * isFull,isEmpty,add,get
 */
@SuppressWarnings(value = "all")
public class ArrayCircleQueueDemo {
    public static void main(String[] args) {

        MyCircleQueue myQueue = new MyCircleQueue(3);
        Scanner scanner = new Scanner(System.in);
        boolean loop = true;

        while (loop) {
            System.out.println("请输入命令：add,head,show");
            String command = scanner.next();
            switch (command) {
                case "add":
                    System.out.println("请输入要添加的element");
                    int element = scanner.nextInt();
                    try {
                        myQueue.add(element);
                    } catch (RuntimeException e) {
                        System.out.println(e.getMessage());
                    }

                    break;
                case "head":
                    try {
                        int head = myQueue.head();
                        System.out.println(head);
                    } catch (RuntimeException e) {
                        System.out.println(e.getMessage());
                    }

                    break;
                case "show":
                    myQueue.show();
                    break;
            }
        }
    }
}

/**
 * 队列：
 * 先进先出，从尾部add，从头部get
 */
@SuppressWarnings(value = "all")
class MyCircleQueue {
    private int[] arr;
    private int first;//指向第一个有效元素
    private int last;//指向最后一个有效元素的下一个位置
    private int maxLength;//最大长度

    public MyCircleQueue(int length) {
        this.arr = new int[3];
        this.maxLength = length;
    }

    public boolean isEmpty() {
        return this.first == this.last;
    }

    public boolean isFull() {
        return this.last - this.first == this.maxLength;
    }

    public void add(int element) {
        if (isFull()) {
            throw new RuntimeException("队列已满");
        }
        this.arr[this.last % this.maxLength] = element;
        this.last++;

    }

    public int head() {
        if (isEmpty()) {
            throw new RuntimeException("队列为空");
        }
        int element = this.arr[this.first % this.maxLength];
        this.first++;
        return element;
    }

    public void show() {
        if (isEmpty()) {
            System.out.println("队列为空");
        }
        for (int i = this.first; i < this.last; i++) {
            System.out.println(this.arr[i%this.maxLength]);
        }
    }

}
